<template>
  <div id="sysType" v-loading="loading">
    <cs-header v-if="loginFlag" ref="header"></cs-header>
    <el-main :style="{height: height}">
      <div class="pernsonal-product-info">
        <div class="personal-info lf">
          <p class="welcome-msg">欢迎 <span>{{ userInfo.user }}</span> 使用「CIDC智能开发云平台」</p>
          <div class="info-details">
            <span class="user-img lf"><i class="iconfont icon-person"></i></span>
            <div class="lf">
              <p>{{ userInfo.user }}</p>
              <p>角色：{{ userInfo.roles }}</p>
              <p>上次登录是时间：{{ dateTime }}</p>
              <p>您可管理的应用数为：{{ userInfo.apps }}</p>
              <div class="modify-password-record-query">
                <span @click="resetPassword">[密码修改]</span>
                <span>[操作记录查询]</span>
              </div>
            </div>
          </div>
        </div>
        <div class="product-info lf">
          <p>移动产品为APP开发，测试，运营及运维提供云到端的一站式解决方案，能有效降低技术门槛，减少研发成本，提升开发效率，协助企业快速搭建稳定高质量的移动应用。</p>
          <ul>
            <li>
            <span>
              <i class="iconfont icon-paper-airplane"></i>
            </span>
              快速开始
            </li>
            <li>
            <span>
              <i class="iconfont icon-chanpin"></i>
            </span>
              产品简介
            </li>
            <li>
            <span>
              <i class="iconfont icon-iconset0118"></i>
            </span>
              产品文档
            </li>
          </ul>
        </div>
      </div>
      <ul class="sysType-list">
        <li v-for="(item, index) in appList" :key="item.app_id" @mouseover="iconShow(index)" @mouseout="iconHide(index)">
          <span v-if="item.isShow && userInfo.version === 1" class="icon">
            <el-tooltip class="item" effect="dark" content="详情" placement="bottom">
              <i class="iconfont icon-paper-airplane" @click="detailsLIst(item)"></i>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="分配" placement="bottom">
              <i class="iconfont icon-optimise" @click="distributionSystem(item)"></i>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
              <i class="iconfont icon-close" @click="deleteApp(item)"></i>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="修改" placement="bottom">
              <i class="iconfont icon-bianji1" @click="editApp(item)"></i>
            </el-tooltip>
          </span>
          <div class="app-info" @click="goSystem(item, item.systemList[0])">
            <p class="app-title">
              <span>{{ index + 1 }}</span>
              {{ item.app_name }}
            </p>
            <ul class="app-data-info">
              <li>
                <p>活跃用户数</p>
                <span>0</span>
              </li>
              <li>
                <p>新增用户</p>
                <span>0</span>
              </li>
              <li>
                <p>设备报活</p>
                <span>0</span>
              </li>
            </ul>
          </div>
          <ul class="system-list">
            <li v-for="obj in item.systemList" :key="obj.sys_no">
              <el-tooltip class="item" effect="dark" :content="obj.sys_name" placement="bottom">
                <i class="iconfont" :class="obj.icon_id" @click="goSystem(item, obj)"></i>
              </el-tooltip>
            </li>
          </ul>
        </li>
        <li v-if="(userInfo.version === 1 || appList.length <= 10) && rbac === 1" class="add-app" @click="addOrEdit">
          <span>
            <i class="iconfont icon-add"></i>
          </span>
          <p>创建应用</p>
        </li>
      </ul>
    </el-main>
    <el-dialog title="编辑应用名称"
               :visible.sync="addRoleDialogVisiable"
               :close-on-click-modal="false"
               width="500px"
               class="roledialog">
      <el-form :model="dialogForm" :rules="rules" ref="dialogForm" label-width="80px" class="demo-dialogForm">
        <el-row>
          <el-col>
            <el-form-item label="应用名称" prop="app_name">
              <el-input v-model="dialogForm.app_name"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item class="dialogbtn">
          <span id="bottom-bar">
            <el-button @click="resetForm('dialogForm')">重置</el-button>
            <el-button @click="cancel">关闭</el-button>
            <el-button type="primary" @click="submitForm('dialogForm')">确定</el-button>
          </span>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="应用详情"
      :visible.sync="dialogVisible"
      width="500px">
      <el-form :model="detailsList" label-width="140px" class="demo-dialogForm">
        <el-row>
            <el-form-item label="应用ID；">
              <span>{{detailsList.app_id}}</span>
            </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="应用名称：">
            <span>{{detailsList.app_name}}</span>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="应用ID[Android]：">
            <span>{{detailsList.android_app_id}}</span>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="应用ID[IOS]：">
            <span>{{detailsList.ios_app_id}}</span>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="创建时间：">
            <span>{{detailsList.app_create_time}}</span>
          </el-form-item>
        </el-row>
      </el-form>
      <div style="text-align: right">
        <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <user-reset-password ref="userResetPassword"></user-reset-password>
    <create-app ref="createAppDialog"></create-app>
    <system-allocation ref="systemAllocation"></system-allocation>
  </div>
</template>

<script>
  import { nextPage, getDateTime } from '../../../assets/js/index'
  import ajax from '../../../api/ajax/ajax'
  import api from '../../../api/url'
  import { mapMutations, mapGetters, mapState } from 'vuex'
  import sysNameObj from '../../../sysNameObj'
  import csHeader from './header'
  import tcHeader from '../other/header'
  import UserResetPassword from '../../systemManager/user/userResetPassword'
  import createApp from './createApp'
  import systemAllocation from './systemAllocation'
  import { Message } from 'element-ui'
  export default {
    name: 'systemList',
    components: {
      csHeader,
      tcHeader,
      UserResetPassword,
      createApp,
      systemAllocation
    },
    data () {
      return {
        detailsList: {},
        dialogVisible: false,
        dialogForm: {},
        currentItem: {},
        addRoleDialogVisiable: false,
        rules: {
          app_name: [
            {required: true, message: '请输入应用名称', trigger: 'blur'}
          ]
        },
        systemList: [],
        system_name: '',
        appList: [],
        loading: false,
        sysNameObj: sysNameObj,
        userInfo: {},
        dateTime: '',
        height: ''
      }
    },
    computed: {
      ...mapGetters([
        'appId',
        'username',
        'rbac'
      ]),
      ...mapState([
        'loginFlag'
      ])
    },
    methods: {
      ...mapMutations([
        'pb_updateSysName',
        'pd_updateSysNo',
        'pd_updateSystemList',
        'pd_updateAppId',
        'pd_updateRBAC'
      ]),
      submitForm (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
              // 修改接口
              ajax.post(api.REFRESH_APP, this.dialogForm).then((res) => {
                this.dialogForm = {}
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                })
              })
            }
            this.addRoleDialogVisiable = false
            this.$refs.dialogForm.clearValidate() // 清除验证
        })
      },
      detailsLIst (item) {
        this.dialogVisible = true
        ajax.post(api.SELECTDETAIL_APPLICATION, { app_id: item.app_id }).then(res => {
          this.detailsList = res.data
        })
      },
      // 创建应用
      addOrEdit () {
        if (this.appList.length < 10) {
          let appDialog = this.$refs.createAppDialog
          appDialog.show({
            onConfirm: (obj) => {
              ajax.post(api.ADD_APP, { app_name: obj.appName }).then(res => {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                appDialog.dialogVisible = false
                this.getAppList()
              })
            }
          })
        } else {
          this.$message.error('对不起！应用不能超过 10 个！')
          return false
        }
      },
      // 修改
      editApp (item) {
        this.dialogForm = item
        this.currentItem = JSON.parse(JSON.stringify(item))
        this.addRoleDialogVisiable = true
      },
      // 关闭
      cancel () {
        this.addRoleDialogVisiable = false
      },
      // 重置
      resetForm () {
        // 如果是编辑进第一个判断
        this.$refs.dialogForm.clearValidate()
        this.dialogForm = {...this.currentItem}
        this.$refs.dialogForm.resetFields()
      },
      // 分配系统
      distributionSystem (item) {
        let distributionDialog = this.$refs.systemAllocation
        distributionDialog.show({
          appId: item.app_id,
          onConfirm: (arr) => {
            let postData = {
              sys_no: arr,
              app_id: item.app_id
            }
            ajax.post(api.APP_ADD_SYS, postData).then(res => {
              this.$message({
                type: 'success',
                message: '分配成功'
              })
              distributionDialog.dialogVisible = false
              this.getAppList()
            })
          }
        })
      },
      // 图标显示
      iconShow (n) {
        this.appList[n].isShow = true
        this.appList.splice(n, 1, this.appList[n])
      },
      // 图标隐藏
      iconHide (n) {
        this.appList[n].isShow = false
        this.appList.splice(n, 1, this.appList[n])
      },
      // 密码修改
      resetPassword (user) {
        let refurp = this.$refs.userResetPassword
        refurp.show({
          onConfirm (password, newPassword, confirmPassword) {
            let postData = {
              password: password,
              newPassword: newPassword,
              confirm_password: confirmPassword // 从form中得
            }
            ajax.post(api.CHANGE_PASSWORD, postData).then(res => {
              Message({
                message: '修改密码成功',
                type: 'success'
              })
              refurp.close()
            }).catch(e => {
              console.error('修改密码发生错误！', e)
            })
          }
        })
      },
      // 退出
      logout () {
        this.$confirm('将退出登录是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          ajax.post(api.LOGOUT).then(res => {
            this.$message({
              type: 'success',
              message: '退出成功!'
            })
            setTimeout(() => {
              window.location.href = '/'
            }, 500)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消退出'
          })
        })
      },
      // 获取应用列表
      getAppList () {
        this.loading = true
        this.appList.splice(0, this.appList.length)
        ajax.post(api.LIST_APP_ID).then(res1 => {
          if (res1.data.length > 0) {
            res1.data.forEach(item => {
              ajax.post(api.GET_SYSTEM_LIST, { app_id: item.app_id }).then(res2 => {
                let arr = res2.data.filter((obj) => {
                  if (obj.isSelected === '1') {
                    return obj
                  }
                })
                this.$set(item, 'systemList', arr)
              })
              this.$set(item, 'isShow', false)
              this.appList.push(item)
              this.loading = false
            })
          }
        })
      },
      // 进入系统
      goSystem (item, obj) {
        this.pd_updateAppId(item.app_id)
        this.pb_updateSysName(obj.sys_name)
        this.pd_updateSysNo(obj.sys_no)
        ajax.post(api.CHANGE_SYS_APP_ID, { appId: item.app_id }).then(res => {})
        ajax.post(api.GO_TO_SYSTEM, { sys_no: obj.sys_no, app_id: item.app_id }).then((res) => {
          if (obj.sys_no === 'M203') { // 发布
            ajax.post('/iap/gotoSetSession', { AppId: this.appId }).then(res => {
              nextPage(obj.sys_url)
            })
          } else if (obj.sys_no === 'M204') { // 网关
            ajax.post('/net/gotoWorkspace').then(res => {})
            nextPage(obj.sys_url)
          } else {
            nextPage(obj.sys_url)
          }
          this.pd_updateSystemList(item.systemList)
        })
      },
      // 删除应用
      deleteApp (item) {
        this.$confirm('删除会导致相关数据丢失，是否删除该应用?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          ajax.post(api.DETELE_APP, [item.app_id]).then((res) => {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.getAppList()
          })
        }).catch(() => {
        })
      }
    },
    created () {
      ajax.post(api.SELECT_USER_INFO).then(res => {
        this.userInfo = res.data
        this.dateTime = getDateTime(new Date(this.userInfo.preTime), 'ss')
        this.$nextTick(() => {
          this.pd_updateRBAC(this.userInfo.version)
          ajax.post(api.IS_FIRST_LOGIN).then(res => {
            if (res.data) {
              this.$confirm('首次登录，请修改密码', '温馨提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.resetPassword()
              }).catch(() => {})
            }
          })
        })
      })
      this.getAppList()
    },
    mounted () {
      let H = document.querySelector('#sysType').clientHeight
      if (this.loginFlag) {
        this.height = H - 50 + 'px'
      } else {
        this.height = H + 'px'
      }
    }
  }
</script>

<style lang="stylus">
  #sysType
    height 100%
    .el-main
      padding 0
      width 100%
      overflow-x scroll
      .pernsonal-product-info
        background #fff
        width 100%
        height 220px
        padding 0
        overflow hidden
        > div
          width 50%
          height 100%
          position relative
        .personal-info
          padding 20px 0 0 130px
          .welcome-msg
            font-size 24px
            margin-bottom 10px
            span
              font-weight bold
          .info-details
            .user-img
              display inline-block
              width 110px
              height 130px
              line-height 130px
              border-radius 6px
              color #ffffff
              text-align center
              background #eeeeee
              margin-right 15px
              .iconfont
                font-size 90px
            div.lf
              position relative
              p:first-child
                font-size 20px
              p + p
                margin 10px 0
              .modify-password-record-query
                position absolute
                top 5px
                right -220px
                span
                  cursor pointer
                  color #016dfb
                span + span
                  margin-left 30px
        .personal-info:after
          content ''
          width 1px
          height 150px
          border-right 1px solid #ddd
          position absolute
          right 0
          top 35px
        .product-info
          padding 60px 135px
          p
            color #767070
          ul
            margin-top 30px
            li
              cursor pointer
              float left
              color #016dfb
              span
                border 1px solid #016dfb
                padding 6px
                border-radius 50%
            li + li
              margin-left 40px
      .sysType-list
        width 1400px
        margin auto
        overflow hidden
        padding-top 30px
        > li
          float left
          width 32%
          height 200px
          background #fff
          margin-bottom 15px
          margin-right 2%
          position relative
          .icon
            position absolute
            top 5px
            right 10px
            i + i
              margin-left 10px
            .iconfont
              font-size 20px
              color #949495
          .app-info
            height 140px
            border-bottom 1px solid #E9E9E9
            .app-title
              padding 20px 0 30px 20px
              span
                display inline-block
                width 40px
                height 40px
                line-height 40px
                text-align center
                background-image url('./../../../images/serial_number.png')
                background-size 100% 100%
                margin-right 5px
                vertical-align middle
            .app-data-info
              overflow hidden
              li
                float left
                width 32%
                text-align center
                p
                  margin-bottom 5px
                  color #999
                span
                  color #404040
                  font-weight bold
              li + li
                margin-left 2%
          .system-list
            height 60px
            display flex
            flex-direction row
            align-items center
            > li
              flex-grow 1
              text-align center
              .iconfont
                font-size 24px
                color #9999A5
        li:nth-child(3n)
          margin-right 0
        .add-app
          text-align center
          padding 30px 0
          span
            display inline-block
            width 100px
            height 100px
            line-height 100px
            border 1px dashed #D9D9D9
            border-radius 50%
            .iconfont
              font-size 50px
              color #D4D4D4
          p
            color #D4D4D4
            margin-top 20px
    .dialogbtn
      text-align right
    .detail-text, .detail-text span
      font-size 16px
</style>
